package com.chenglu.android.orderinfo;

import android.content.ClipData;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Base64;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.Toolbar;
import androidx.core.content.ContextCompat;
import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chenglu.android.R;
import com.chenglu.android.common.base.BaseApplication;
import com.chenglu.android.common.base.BaseFullScreenActivity;
import com.chenglu.android.common.base.Global;
import com.chenglu.android.common.net.Constant;
import com.chenglu.android.common.utils.BaseDialog;
import com.chenglu.android.common.utils.ClipboardUtil;
import com.chenglu.android.common.utils.GlideUtils;
import com.chenglu.android.common.utils.LogUtils;
import com.chenglu.android.common.utils.SPUtils;
import com.chenglu.android.common.utils.StatusBarUtil;
import com.chenglu.android.common.utils.ToastUtils;
import com.chenglu.android.common.utils.Utils;
import com.chenglu.android.goodsinfo.infoutils.GoodsInfoUtils;
import com.chenglu.android.logistics.LogisticsActivity;
import com.chenglu.android.mine.bean.CommonDataBean;
import com.chenglu.android.mine.login.LoginActivity;
import com.chenglu.android.order.TextStatusUtils;
import com.chenglu.android.order.bean.OrderInfoBean;
import com.chenglu.android.order.mvp.contract.OrderContract;
import com.chenglu.android.order.mvp.presenter.OrderPresenter;
import com.chenglu.android.ordercomment.OrderCommentActivity;
import com.chenglu.android.orderinfo.adapter.OrderInfoAdapter;
import com.chenglu.android.orderinfo.adapter.QrcodeListAdapter;
import com.chenglu.android.orderinfo.bean.OrderDetailBean;
import com.chenglu.android.orderinfo.bean.QrCodeListBean;
import com.chenglu.android.orderinfo.bean.QrcodeBean;
import com.chenglu.android.payment.PayUtils;
import com.chenglu.android.payment.adapter.OrderPaytypeAdapter;
import com.chenglu.android.payment.bean.Address;
import com.chenglu.android.payment.bean.CouponListBean;
import com.chenglu.android.payment.bean.PayOrderBean;
import com.chenglu.android.payment.bean.TenantIdPayMethod;
import com.google.gson.Gson;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.journeyapps.barcodescanner.BarcodeEncoder;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.animator.PopupAnimator;
import com.lxj.xpopup.core.BottomPopupView;
import com.lxj.xpopup.core.CenterPopupView;
import com.lxj.xpopup.interfaces.OnConfirmListener;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @author: lyj
 * @Created: by Copyright 2023 3 Guangzhou Hongma Technology Co., Ltd. All rights reserved.
 * @Description：订单详情页
 */
public class OrderInfoActivity extends BaseFullScreenActivity<OrderPresenter> implements OrderContract.View {

    public static final String GOODSRECORDS = "GOODSRECORDS";
    public static final String ORDERID = "orderId";
    public static final String ORDERNO = "orderNo";

    public static final String SHOPSTYPEID = "SHOPSTYPEID";

    @BindView(R.id.iv_header)
    FrameLayout ivHeader;
    @BindView(R.id.tv_address_status)
    TextView tvAddressStatus;
    @BindView(R.id.tv_order_destag)
    TextView tvOrderDestag;
    @BindView(R.id.iv_address_status)
    ImageView ivAddressStatus;
    @BindView(R.id.rl_address_status)
    RelativeLayout rlAddressStatus;
    @BindView(R.id.iv_order_phone)
    ImageView ivOrderPhone;
    @BindView(R.id.tv_order_name)
    TextView tvOrderName;
    @BindView(R.id.tv_order_phone)
    TextView tvOrderPhone;
    @BindView(R.id.ll_name_phone)
    LinearLayout llNamePhone;
    @BindView(R.id.ll_phone)
    LinearLayout llPhone;
    @BindView(R.id.iv_order)
    ImageView ivOrder;
    @BindView(R.id.tv_order_address)
    TextView tvOrderAddress;
    @BindView(R.id.ll_address)
    LinearLayout llAddress;
    @BindView(R.id.iv_right)
    ImageView ivRight;
    @BindView(R.id.rl_order_address)
    RelativeLayout rlOrderAddress;
    @BindView(R.id.iv_cart_seller)
    ImageView ivCartSeller;
    @BindView(R.id.tv_cart_sellername)
    TextView tvCartSellername;
    @BindView(R.id.rv_pay_info)
    RecyclerView rvPayInfo;
    @BindView(R.id.tv_order_info_money)
    TextView tvOrderInfoMoney;
    @BindView(R.id.tv_order_info_logisticsFee)
    TextView tvOrderInfoLogisticsFee;
    @BindView(R.id.tv_order_info_youhui_money)
    TextView tvOrderInfoYouhuiMoney;
    @BindView(R.id.rl_youhui_money)
    RelativeLayout rlYouhuiMoney;
    @BindView(R.id.tv_order_info_member_money)
    TextView tvOrderInfoMemberMoney;
    @BindView(R.id.rl_member_money)
    RelativeLayout rlMemberMoney;
    @BindView(R.id.tv_order_info_actual_price)
    TextView tvOrderInfoActualPrice;
    @BindView(R.id.iv_bean)
    ImageView ivBean;
    @BindView(R.id.fl_redbean)
    FrameLayout flRedbean;
    @BindView(R.id.tv_buy_bean)
    TextView tvBuyBean;
    @BindView(R.id.tv_get)
    TextView tvGet;
    @BindView(R.id.tv_red_bean)
    TextView tvRedBean;
    @BindView(R.id.tv_red_bean_info)
    TextView tvRedBeanInfo;
    @BindView(R.id.ll_order_equity)
    LinearLayout llOrderEquity;
    @BindView(R.id.tv_order_remarks_edit)
    TextView tvOrderRemarksEdit;
    @BindView(R.id.tv_peisong_mothed)
    TextView tvPeisongMothed;
    @BindView(R.id.tv_order_info_number)
    TextView tvOrderInfoNumber;
    @BindView(R.id.tv_copy)
    TextView tvCopy;
    @BindView(R.id.ll_order_number)
    RelativeLayout llOrderNumber;
    @BindView(R.id.tv_order_info_time)
    TextView tvOrderInfoTime;
    @BindView(R.id.ll_xiadan_time)
    RelativeLayout llXiadanTime;
    @BindView(R.id.tv_order_info_way)
    TextView tvOrderInfoWay;
    @BindView(R.id.tv_order_info_paytime)
    TextView tvOrderInfoPaytime;
    @BindView(R.id.ll_pay_time)
    RelativeLayout llPayTime;
    @BindView(R.id.tv_order_info_give_reddou)
    TextView tvOrderInfoGiveReddou;
    @BindView(R.id.rl_pay_no)
    RelativeLayout rlPayNo;
    @BindView(R.id.tv_order_info_delivery_time)
    TextView tvOrderInfoDeliveryTime;
    @BindView(R.id.ll_delivery_time)
    RelativeLayout llDeliveryTime;
    @BindView(R.id.tv_order_info_finish_time)
    TextView tvOrderInfoFinishTime;
    @BindView(R.id.ll_finish_time)
    RelativeLayout llFinishTime;
    @BindView(R.id.tv_order_info_express_firm)
    TextView tvOrderInfoExpressFirm;
    @BindView(R.id.ll_express_firm)
    RelativeLayout llExpressFirm;
    @BindView(R.id.tv_order_info_express_number)
    TextView tvOrderInfoExpressNumber;
    @BindView(R.id.tv_copy_express_number)
    TextView tvCopyExpressNumber;
    @BindView(R.id.ll_express)
    RelativeLayout llExpress;
    @BindView(R.id.scrollView)
    NestedScrollView scrollView;
    @BindView(R.id.tv_order_btn3)
    TextView tvOrderBtn3;
    @BindView(R.id.tv_order_btn1)
    TextView tvOrderBtn1;
    @BindView(R.id.tv_order_btn2)
    TextView tvOrderBtn2;
    @BindView(R.id.rl_order_comment)
    RelativeLayout rlOrderComment;
    @BindView(R.id.ll_loading_data)
    LinearLayout llLoadingData;
    @BindView(R.id.ic_back)
    ImageView icBack;
    @BindView(R.id.ll_back)
    LinearLayout llBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.rl_title)
    RelativeLayout rlTitle;
    @BindView(R.id.ll_shop_text)
    LinearLayout llShopText;
    @BindView(R.id.tv_pickup_name)
    TextView tvPickupName;
    @BindView(R.id.tv_packing_fee)
    TextView tvPackingFee;
    @BindView(R.id.rl_packing_fee)
    RelativeLayout rlPackingFee;
    @BindView(R.id.tv_delivery_fee)
    TextView tvDeliveryFee;
    @BindView(R.id.rl_delivery_fee)
    RelativeLayout rlDeliveryFee;
    @BindView(R.id.rl_dining_method)
    RelativeLayout rlDiningMethod;
    @BindView(R.id.tv_dining_time)
    TextView tvDiningTime;
    @BindView(R.id.rl_dining_time)
    RelativeLayout rlDiningTime;
    @BindView(R.id.tv_trade_time)
    TextView tvTradeTime;
    @BindView(R.id.rl_trade_time)
    RelativeLayout rlTradeTime;
    @BindView(R.id.tv_business_adderss)
    TextView tvBusinessAdderss;
    @BindView(R.id.rl_business_address)
    RelativeLayout rlBusinessAddress;
    @BindView(R.id.tv_order_remark)
    TextView tvOrderRemark;
    @BindView(R.id.rl_order_remark)
    RelativeLayout rlOrderRemark;
    @BindView(R.id.tv_order_tableware)
    TextView tvOrderTableware;
    @BindView(R.id.rl_order_tableware)
    RelativeLayout rlOrderTableware;
    @BindView(R.id.tv_dining_time_title)
    TextView tvDiningTimeTitle;
    @BindView(R.id.tv_dining_title_method)
    TextView tvDiningTitleMethod;
    @BindView(R.id.rl_yunfei)
    RelativeLayout rlYunfei;
    @BindView(R.id.rv_code)
    RecyclerView rvCode;
    @BindView(R.id.rl_code_recyclerView)
    RelativeLayout rlCodeRecyclerView;

    private OrderInfoAdapter orderadapter;

    String ordrshippingNo; //快递单号

    String orderId, orderNo; //订单id
    int shopsTypeId;
    String aaccessToken;
    //订单的客服数据
    private OrderDetailBean.Data.OrderDetails.GoodsVO orderDetail;

    //订单的实际价格
    private String orderActualPrice;

    String getCreateTime;

    OrderInfoBean.Data.Records records;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        setContentView(R.layout.activity_order_info);
        ButterKnife.bind(this);
        StatusBarUtil.immersive(this);
        StatusBarUtil.setPaddingSmart(this, toolbar);
        initScroolview();
        initView1();
    }

    protected void initView1() {


        mPresenter = new OrderPresenter();
        mPresenter.attachView(this);

        orderId = getIntent().getStringExtra(ORDERID);
        orderNo = getIntent().getStringExtra(ORDERNO);

        shopsTypeId = getIntent().getIntExtra(SHOPSTYPEID, 0);

        records = (OrderInfoBean.Data.Records) getIntent().getSerializableExtra(GOODSRECORDS);

        LogUtils.e("JSONGoods" + new Gson().toJson(records));
        aaccessToken = SPUtils.getString("AaccessToken", "AaccessToken");

        initAdapter();

        initCodeAdapter();

    }

    @Override
    protected void onResume() {
        super.onResume();

        dataList.clear();
        mPresenter.getOrderInfo(getToken(), orderId, shopsTypeId);


    }

    private QrcodeListAdapter qrcodeListAdapter;

    List<QrCodeListBean.QrCodeList> qrCodeLists = new ArrayList<>();


    private int mCodePosition;

    private void initCodeAdapter() {
//
        qrcodeListAdapter = new QrcodeListAdapter(this, R.layout.item_qrcode, qrCodeLists);
        rvCode.setLayoutManager(new LinearLayoutManager(this));
        rvCode.setAdapter(qrcodeListAdapter);

        qrcodeListAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                //弹出对话框
                mCodePosition = position;
                if (shopsTypeId == Constant.typeIdBeauty || shopsTypeId == Constant.typeIdEducation) {
                    //请求核销码
                    mPresenter.getQrCodeInfo(getToken(), qrcodeListAdapter.getData().get(position).getId(), shopsTypeId);
                }
            }
        });
    }

    private List<OrderDetailBean.Data.OrderDetails> dataList = new ArrayList<>();


    private void initAdapter() {

        orderadapter = new OrderInfoAdapter(this, R.layout.item_comfirm_order_cart, dataList);
        rvPayInfo.setLayoutManager(new LinearLayoutManager(this));
        rvPayInfo.setAdapter(orderadapter);


        orderadapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                //跳转详情页
//                Intent intent = new Intent(mContext, GoodsInfoActivity.class);
//                intent.putExtra("categoryId", orderadapter.getItem(position).getOrderDetail().getCategoryId());
//                intent.putExtra("id", orderadapter.getItem(position).getGoodsId());
//                startActivity(intent);
            }
        });
    }

    @Override
    public void onEmpty(Object tag) {
        super.onEmpty(tag);
        llLoadingData.setVisibility(View.GONE);
        finish();
//        showEmptyView(tag.toString());


    }


    //是否显示售后
    private boolean isShouhou;
    private OrderDetailBean orderDetailBean;


    /*订单详情页的回调数据*/
    @Override
    public void getOrderInfo(OrderDetailBean bean) {

        if (!dataList.isEmpty()) {
            dataList.clear();
        }

        if (bean.getData() != null) {
            LogUtils.d("走这里显示了~~");
            orderDetailBean = bean;
            getCreateTime = bean.getData().getCreateTime();
            llLoadingData.setVisibility(View.VISIBLE);

            GlideUtils.setImageView(mContext, bean.getData().getLogoImage(), ivCartSeller);

            //订单备注
            if (TextUtils.isEmpty(bean.getData().getRemark())) {
                tvOrderRemark.setText("无备注");
            } else {
                tvOrderRemark.setText(bean.getData().getRemark());
            }

            //美业和教育 把运费隐藏
            if (bean.getData().getShopsTypeId() == Constant.typeIdBeauty || bean.getData().getShopsTypeId() == Constant.typeIdEducation) {
                rlYunfei.setVisibility(View.GONE);
            } else {
                rlYunfei.setVisibility(View.VISIBLE);
            }

            //根据 餐饮、便利店、药店、孕育判断是否显示
            // ["就餐时间", "自取时间", "送达时间"][self.model.cyExtVo.repastWay.rawValue]
//             ["到店堂食", "到店自取", "外卖配送"][self.model.cyExtVo.repastWay.rawValue]
            if (bean.getData().getShopsTypeId() == Constant.typeIdRestaurant || bean.getData().getShopsTypeId() == Constant.typeIdMinimart
                    || bean.getData().getShopsTypeId() == Constant.typeIdPharmaceuticals || bean.getData().getShopsTypeId() == Constant.typeIdBreed) {
//                ExtContent extContent = new Gson().fromJson(bean.getData().getExtContent(), ExtContent.class);
                if (bean.getData().getCyExtVo() == null) {
                    return;
                }

                rlDiningTime.setVisibility(View.VISIBLE);  //就餐时间
                rlDiningMethod.setVisibility(View.VISIBLE); //p配送方式
                rlTradeTime.setVisibility(View.VISIBLE); //营业时间
                rlBusinessAddress.setVisibility(View.VISIBLE); //商家地址

                rlDeliveryFee.setVisibility(View.VISIBLE); //配送费
                rlPackingFee.setVisibility(View.VISIBLE); //包装费

                tvDiningTime.setText(bean.getData().getCyExtVo().getMealTime());
                tvTradeTime.setText(bean.getData().getBusinessTime());
                tvBusinessAdderss.setText(bean.getData().getShopsAddress());
                tvDeliveryFee.setText("¥" + Utils.formatZeroNumber(bean.getData().getCyExtVo().getTransportFee())); //配送费
                tvPackingFee.setText("¥" + Utils.formatZeroNumber(bean.getData().getCyExtVo().getPackageFee())); //包装费

                if (bean.getData().getShopsTypeId() == Constant.typeIdRestaurant) {
                    tvDiningTitleMethod.setText("就餐方式");
                    rlOrderTableware.setVisibility(View.VISIBLE);
                    if (bean.getData().getCyExtVo().getTablewareCount() > 0) {
                        tvOrderTableware.setText(bean.getData().getCyExtVo().getTablewareCount() + "份餐具");
                    } else {
                        tvOrderTableware.setText("无需餐具");
                    }

                } else {
                    tvDiningTitleMethod.setText("物流方式");
                    rlOrderTableware.setVisibility(View.GONE);
                }

                switch (bean.getData().getCyExtVo().getRepastWay()) {
                    case 0:
                        tvPeisongMothed.setText("到店堂食");
                        tvDiningTimeTitle.setText("就餐时间");
                        break;
                    case 1:
                        tvPeisongMothed.setText("到店自取");
                        tvDiningTimeTitle.setText("自取时间");
                        break;
                    case 2:
                        tvPeisongMothed.setText("外卖配送");
                        tvDiningTimeTitle.setText("送达时间");
                        break;
                }


            }

            // 设置订单按钮的颜色
            TextStatusUtils.setBtn2Colors(mContext, tvOrderBtn2, bean.getData().getOrderType());

            TextStatusUtils.setfooterBtn(mContext, bean.getData().getShopsTypeId(), bean.getData().getStatus(), bean.getData().getExtStatus(), tvOrderBtn1, tvOrderBtn2, tvOrderBtn3);

            if (bean.getData().getCyExtVo() != null) {
                //设置状态
                TextStatusUtils.setOrderImageView(mContext, bean.getData().getShopsTypeId(), bean.getData().getStatus(), 0, bean.getData().getExtStatus()
                        , bean.getData().getCyExtVo().getTakeFoodNo(), tvOrderDestag, tvAddressStatus, tvPickupName, ivAddressStatus);
            } else {
                //设置状态
                TextStatusUtils.setOrderImageView(mContext, bean.getData().getShopsTypeId(), bean.getData().getStatus(), 0, bean.getData().getExtStatus()
                        , "", tvOrderDestag, tvAddressStatus, tvPickupName, ivAddressStatus);
            }

            //地址选择
            if (bean.getData().getShopsTypeId() == Constant.typeIdShop)
                if (bean.getData().getAddress().isEmpty()) {
                    llPhone.setVisibility(View.GONE);
                    llAddress.setVisibility(View.GONE);
                    tvOrderName.setVisibility(View.GONE);
                    tvOrderPhone.setVisibility(View.GONE);
                    tvOrderAddress.setVisibility(View.GONE);
                } else {
                    Address userAddress = new Gson().fromJson(bean.getData().getAddress(), Address.class);
                    llPhone.setVisibility(View.VISIBLE);
                    llAddress.setVisibility(View.VISIBLE);
                    tvOrderName.setVisibility(View.VISIBLE);
                    tvOrderPhone.setVisibility(View.VISIBLE);
                    tvOrderAddress.setVisibility(View.VISIBLE);
                    tvOrderName.setText(userAddress.getConsignee());
                    tvOrderPhone.setText(Utils.getStarMobile(userAddress.getMobile()));
                    tvOrderAddress.setText(userAddress.getProvince() + " " + userAddress.getCity() + " " + userAddress.getDistrict() + " "
                            + userAddress.getAddress());
                    LogUtils.d("进来~~~");
                }


            //判断美业核销码
            if (shopsTypeId == Constant.typeIdBeauty) {
                rlCodeRecyclerView.setVisibility(View.VISIBLE);
                rvCode.setVisibility(View.VISIBLE);
                for (int i = 0; i < bean.getData().getBeautyOrderCodeDTOList().size(); i++) {

                    OrderDetailBean.Data.BeautyOrderCodeDTOList bDList = bean.getData().getBeautyOrderCodeDTOList().get(i);
                    QrCodeListBean.QrCodeList qr = new QrCodeListBean.QrCodeList();
                    LogUtils.e("name=" + bDList.getName());
                    qr.setName(bDList.getName());
                    qr.setId(bDList.getId());
                    qr.setStatus(bDList.getStatus());
                    qr.setUseTime(bDList.getUseTime());
                    qr.setCreateTime(bDList.getCreateTime());
                    qrCodeLists.add(qr);
                }
                LogUtils.e("qrcode" + qrCodeLists.size());

                qrcodeListAdapter.notifyDataSetChanged();
            }

            if (shopsTypeId == Constant.typeIdEducation) {
                rlCodeRecyclerView.setVisibility(View.VISIBLE);
                rvCode.setVisibility(View.VISIBLE);
                for (int i = 0; i < bean.getData().getEducationOrderCodeDTOList().size(); i++) {
                    OrderDetailBean.Data.EducationOrderCodeDTOList bDList = bean.getData().getEducationOrderCodeDTOList().get(i);
                    QrCodeListBean.QrCodeList qr = new QrCodeListBean.QrCodeList();
                    qr.setName(bDList.getName());
                    qr.setId(bDList.getId());
                    qr.setStatus(bDList.getStatus());
                    qr.setUseTime(bDList.getUseTime());
                    qr.setCreateTime(bDList.getCreateTime());
                    qrCodeLists.add(qr);
                }
                qrcodeListAdapter.notifyDataSetChanged();
            }

        }

        tvOrderInfoMemberMoney.setText("¥" + Utils.formatZeroNumber(bean.getData().getOrderMemberCardDiscountAmount()));

        tvOrderInfoYouhuiMoney.setText("¥" + Utils.formatZeroNumber(bean.getData().getOrderDiscountAmount())); //优惠金额

//        bean.getData().getOrderMemberCardDiscountAmount()

        tvOrderInfoGiveReddou.setText(bean.getData().getTotalGiveBeans() + "");  //赠送红豆

        tvOrderInfoLogisticsFee.setText("¥" + Utils.formatZeroNumber(bean.getData().getFreight()));

        if (bean.getData().getPayType() == 1) {
            tvOrderInfoWay.setText("支付宝支付");
        } else if (bean.getData().getPayType() == 2) {
            tvOrderInfoWay.setText("微信支付");
        } else if (bean.getData().getPayType() == 3) {
            tvOrderInfoWay.setText("余额支付");
        } else if (bean.getData().getPayType() == 5) {
            tvOrderInfoWay.setText("快捷支付");
        } else if (bean.getData().getPayType() == 4) {
            tvOrderInfoWay.setText("积分支付");
        } else if (bean.getData().getPayType() == 0) {
            tvOrderInfoWay.setText("待付款");
        } else if (bean.getData().getPayType() == 6) {
            tvOrderInfoWay.setText("会员卡支付");
        }


        orderActualPrice = bean.getData().getOrderActuallyPaid();
        //商品金额-优惠金额

        tvOrderInfoMoney.setText("¥" + Utils.formatZeroNumber(bean.getData().getOrderAmount())); //商品价格

        tvOrderInfoActualPrice.setText("¥" + Utils.formatZeroNumber(orderActualPrice));//实际支付


        if (bean.getData().getTotalGiveBeans() > 0) {
            llOrderEquity.setVisibility(View.VISIBLE);
            tvRedBean.setText(Utils.doubleTrans2(bean.getData().getTotalGiveBeans()) + "");
        } else {
            llOrderEquity.setVisibility(View.GONE);
        }

        if (bean.getData().getPayNo().isEmpty()) {
            rlPayNo.setVisibility(View.GONE);
        } else {
            rlPayNo.setVisibility(View.VISIBLE);
            tvOrderInfoGiveReddou.setText(bean.getData().getPayNo());
        }
        if (bean.getData().getOrderNo().isEmpty()) {
            llOrderNumber.setVisibility(View.GONE);
        } else {
            llOrderNumber.setVisibility(View.VISIBLE);
            tvOrderInfoNumber.setText("" + bean.getData().getOrderNo()); //订单编号
//                orderInfoNo = bean.getData().getOrderNo();
        }

        if (bean.getData().getCreateTime().isEmpty()) {
            llXiadanTime.setVisibility(View.GONE);
        } else {
            llXiadanTime.setVisibility(View.VISIBLE);
            tvOrderInfoTime.setText("" + bean.getData().getCreateTime());//下单时间
        }

        if (bean.getData().getPayTime().isEmpty()) {
            llPayTime.setVisibility(View.GONE);
        } else {
            llPayTime.setVisibility(View.VISIBLE);
            tvOrderInfoPaytime.setText("" + bean.getData().getPayTime());//付款时间
        }


        if (bean.getData().getSendTime().isEmpty()) {
            llDeliveryTime.setVisibility(View.GONE);
        } else {
            llDeliveryTime.setVisibility(View.VISIBLE);
            tvOrderInfoDeliveryTime.setText("" + bean.getData().getSendTime());//发货时间
        }

        if (bean.getData().getShippingName().isEmpty()) {
            llExpressFirm.setVisibility(View.GONE);
        } else {
            llExpressFirm.setVisibility(View.VISIBLE);
            tvOrderInfoExpressFirm.setText("" + bean.getData().getShippingName()); //快递公司
        }

        if (bean.getData().getShippingNo().isEmpty()) {
            llExpress.setVisibility(View.GONE);
        } else {
            llExpress.setVisibility(View.VISIBLE);
            ordrshippingNo = bean.getData().getShippingNo();
            tvOrderInfoExpressNumber.setText("" + bean.getData().getShippingNo());//快递单号
        }

//            Glide.with(context).load(bean.getData().getSellerLogo()).into(ivCartSeller);//商品图标
        tvCartSellername.setText(bean.getData().getShopsName());//店铺名称

        //添加数据
        for (int i = 0; i < bean.getData().getOrderDetails().size(); i++) {
            dataList.add(bean.getData().getOrderDetails().get(i));

        }

//        for (int i = 0; i < bean.getData().getOrderDetails().size(); i++) {
//            if (bean.getData().getOrderDetails().get(i).getRefundStatus() > 0) {
//                isShouhou = true;
//                break;
//            } else {
//                isShouhou = false;
//            }
//        }
//        if (bean.getData().getPayStatus() == 1 && isShouhou) {
//            llOrderShouhou.setVisibility(View.GONE);
//        } else {
//            llOrderShouhou.setVisibility(View.GONE);
//        }
        orderadapter.notifyDataSetChanged();

        //订单的客户数据
        orderDetail = bean.getData().getOrderDetails().get(0).getGoodsVO();


    }

    private QrCodeCenterPopup qrCodeCenterPopup;

    //核销码
    @Override
    public void getQrCodeInfo(QrcodeBean bean) {
        //弹出对话框
        qrCodeCenterPopup = new QrCodeCenterPopup(this);
        qrCodeCenterPopup.setQrcodeBean(bean);
        new XPopup.Builder(this)
                .moveUpToKeyboard(false)
                .enableDrag(false)
                .animationDuration(150)
                .asCustom(qrCodeCenterPopup)
                .show();
    }


    @Override
    public void onError(String errorMsg) {
        isLogin = false;
        SPUtils.setBoolean("ISLOGIN", false);

        showXPopupView(mContext, "提示", "登录已过期,请重新登录", "登录");
    }

    @Override
    public void getCouponList(CouponListBean bean) {

    }


    @Override
    public void getPayOrder(PayOrderBean bean) {
        ToastUtils.show("支付成功");
        mPresenter.getOrderInfo(aaccessToken, orderId, shopsTypeId);
    }

    @Override
    public void getOrderList(OrderInfoBean bean) {

    }

    @Override
    public void getOrderCancel(CommonDataBean bean) {

        ToastUtils.show("取消成功");
        mPresenter.getOrderInfo(aaccessToken, orderId, shopsTypeId);
    }


    @Override
    public void getOrderRemove(CommonDataBean bean) {
        ToastUtils.show("删除成功");
        mPresenter.getOrderInfo(aaccessToken, orderId, shopsTypeId);
    }


    @Override
    public void getOrderReceiving(CommonDataBean bean) {

        ToastUtils.show(bean.getMsg());
        mPresenter.getOrderInfo(aaccessToken, orderId, shopsTypeId);
    }


    private int mOffset = 0;
    private int mScrollY = 0;

    private void initScroolview() {


        scrollView.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
            int lastScrollY = 0;
            int h = Global.dp2px(80);
            int color = ContextCompat.getColor(getApplicationContext(), R.color.white) & 0x00ffffff;

            @Override
            public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {

                if (lastScrollY < h) {
                    scrollY = Math.min(h, scrollY);
                    mScrollY = scrollY > h ? h : scrollY;
//                    buttonBarLayout.setAlpha(1f * mScrollY / h);
                    toolbar.setBackgroundColor(((255 * mScrollY / h) << 24) | color);
                    ivHeader.setTranslationY(mOffset - mScrollY);
                }
                if (scrollY == 0) {
                    tvTitle.setTextColor(getResources().getColor(R.color.transparent));
//                    llBlindBgsearch.setBackground(getResources().getDrawable(R.drawable.store_left_boom_shape_30));
                    icBack.setBackgroundResource(R.drawable.ic_black_back);

                } else {
                    tvTitle.setTextColor(getResources().getColor(R.color.color_333333));
//                    llBlindBgsearch.setBackground(getResources().getDrawable(R.drawable.store_left_top_shape_30));
                    icBack.setBackgroundResource(R.drawable.ic_black_back);
                    tvTitle.setText("订单详情");

                }

                lastScrollY = scrollY;
            }
        });
        toolbar.setBackgroundColor(0);


    }

    @OnClick({R.id.tv_copy, R.id.tv_copy_express_number, R.id.ll_back, R.id.tv_order_btn1, R.id.tv_order_btn2, R.id.tv_order_btn3})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_copy:

                BaseApplication.getClipboardManager().setPrimaryClip(ClipData.newPlainText("text", orderId));
                ToastUtils.show("复制成功");
                LogUtils.d("dddd" + ClipboardUtil.getText(mContext, orderId));

                break;
            case R.id.tv_copy_express_number:
                BaseApplication.getClipboardManager().setPrimaryClip(ClipData.newPlainText("text", ordrshippingNo));
                ToastUtils.show("复制成功");
                LogUtils.d("文本内容22222" + ClipboardUtil.getText(mContext, ordrshippingNo));
                break;

//            case R.id.ll_order_shouhou:
            //
//                Integer orderStatus = orderDetailBean.getData().getOrderStatus();
//
////                 //未付款和已取消不能点击申请售后详情
//                if (orderStatus == 0 || orderStatus == -1) {
//                    ToastUtils.show("当前订单不可以退款");
//                } else {
//                    //已付款 售后中 已发货 已退状态 可以查看申请售后详情
//                    if (orderStatus == 1 || orderStatus == 2 || orderStatus == -2 || orderStatus == -3) {
//                        startActivity(new Intent(this, ReFundsalesAcvtivity.class)
//                                .putExtra(ReFundsalesAcvtivity.ORDERNO, orderInfoNo));
//                    } else if (orderStatus == 3 || orderStatus == 4) {
//                        //去请求接口信息
//                        mPresenter.getOrderInfoRefundLogCount(aaccessToken, orderInfoNo);
//                    } else {
//                        ToastUtils.show("当前订单不可以退款");
//                    }
//                }


//                break;
            case R.id.ll_back:
                finish();
                break;

            case R.id.tv_order_btn1:
                String tv1 = tvOrderBtn1.getText().toString();
                if (tv1.equals(getResources().getString(R.string.order_cancel))) {

                    BaseDialog.showDialog(mContext, "是否取消订单", "取消", "确定", new OnConfirmListener() {
                        @Override
                        public void onConfirm() {

                            //取消订单的接口
                            mPresenter.getOrderCancel(aaccessToken, orderId);

                        }
                    }, false);

                } else if (tv1.equals(getResources().getString(R.string.order_look_logistics))) {
                    //查看物流
                    Intent intent = new Intent(mContext, LogisticsActivity.class);
                    intent.putExtra("orderNo", orderNo);
                    startActivity(intent);

                } else if (tv1.equals(getResources().getString(R.string.order_delete))) {
                    LogUtils.e("删除订单id=" + orderId);
                    BaseDialog.showDialog(mContext, "是否删除订单", "取消", "确定", new OnConfirmListener() {
                        @Override
                        public void onConfirm() {
//                                    LogUtils.e("删除订单id="+ allAdapter.getData().get(position).getId());
                            //取消订单的接口
                            mPresenter.getOrderRemove(aaccessToken, orderId);

                        }
                    }, false);
                } else if (tv1.equals(mContext.getResources().getString(R.string.order_comment_message))) {
                    Intent commentInent = new Intent(mContext, OrderCommentActivity.class);
                    Bundle bundle = new Bundle();
//                    OrderInfoBean.Data.Records records = allAdapter.getData().get(position);
                    bundle.putSerializable(OrderCommentActivity.ORDERLIST, records);
                    commentInent.putExtra(OrderCommentActivity.ORDERNO, orderNo);
                    commentInent.putExtras(bundle);
                    mContext.startActivity(commentInent);
                }
                break;
            case R.id.tv_order_btn2:
                String tv2 = tvOrderBtn2.getText().toString();

                if (tv2.equals("评价")) {

                    Intent commentInent = new Intent(mContext, OrderCommentActivity.class);
                    Bundle bundle = new Bundle();
//                    OrderInfoBean.Data.Records records = ;
                    bundle.putSerializable(OrderCommentActivity.ORDERLIST, records);
                    commentInent.putExtra(OrderCommentActivity.ORDERNO, orderNo);
                    commentInent.putExtras(bundle);
                    mContext.startActivity(commentInent);
                }
                //再次购买
                else if (tv2.equals(getResources().getString(R.string.order_buy_again))) {
                    if (!orderDetailBean.getData().getOrderDetails().isEmpty()) {
                        GoodsInfoUtils.goodsInfo(mContext, orderDetailBean.getData().getOrderDetails().get(0).getGoodsId()
                        ,shopsTypeId);
                    }
                    //立即支付
                } else if (tv2.equals(getResources().getString(R.string.order_immediate_payment))) {
                    //弹出付款对话框
                    mPresenter.getenantIdPayMethod(aaccessToken, Constant.APPCLIENT, orderDetailBean.getData().getTenantId());

                } else if (tv2.equals(getResources().getString(R.string.order_confirm_receipt))) {
                    //确认收货
                    mPresenter.getOrderReceiving(aaccessToken, orderId);
                }
                break;
            case R.id.tv_order_btn3:
                String tv3 = tvOrderBtn3.getText().toString();
                ToastUtils.show("近期开放");
                break;
        }
    }


    BottomPopup showpayTypePopup;

    @Override
    public void getenantIdPayMethod(TenantIdPayMethod bean) {
        //弹出支付的对话框
        showpayTypePopup = new BottomPopup(this);
        showpayTypePopup.setPayMethodList(bean.getData());
        new XPopup.Builder(this)
                .moveUpToKeyboard(false)
                .enableDrag(false)
                .animationDuration(150)
                .asCustom(showpayTypePopup)
                .show();

    }

    //对话框选择的参数类型
    int payTpyeWay = 0;
    private int mPayposition;
    private OrderPaytypeAdapter orderPaytypeAdapter;

    class BottomPopup extends BottomPopupView {

        ImageView ivDialogDelete;
        Button btnPayOrder;
        RecyclerView rvPay;

        //注意：自定义弹窗本质是一个自定义View，但是只需重写一个参数的构造，其他的不要重写，所有的自定义弹窗都是这样。
        public BottomPopup(@NonNull Context context) {
            super(context);
        }

        // 返回自定义弹窗的布局
        @Override
        protected int getImplLayoutId() {
            return R.layout.dialog_pay_order;
        }

        // 执行初始化操作，比如：findView，设置点击，或者任何你弹窗内的业务逻辑
        @Override
        protected void onCreate() {
            super.onCreate();
            //创建的时候默认的金豆支付


            ivDialogDelete = findViewById(R.id.iv_dialog_delete);
            btnPayOrder = findViewById(R.id.btn_pay_order);
            rvPay = findViewById(R.id.rv_pay);

            orderPaytypeAdapter = new OrderPaytypeAdapter(mContext, R.layout.item_pay_method, payMethodList);
            rvPay.setLayoutManager(new LinearLayoutManager(mContext));
            rvPay.setAdapter(orderPaytypeAdapter);
            orderPaytypeAdapter.setThisPosition(0);
            orderPaytypeAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(BaseQuickAdapter baseQuickAdapter, View view, int position) {
                    mPayposition = position;
                    orderPaytypeAdapter.setThisPosition(position);

                }
            });

            btnPayOrder.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
//                    需要二次确认
                    dismiss();
                    BaseDialog.showDialog(mContext, "确定使用" + orderPaytypeAdapter.getData().get(mPayposition).getDescriptions() + "支付吗", "取消", "确定", new OnConfirmListener() {
                        @Override
                        public void onConfirm() {

                            JSONObject jsonObject = PayUtils.setPayParam(orderNo, orderPaytypeAdapter.getData().get(mPayposition).getPayType(), orderPaytypeAdapter.getData().get(mPayposition).getId());

                            mPresenter.getPayOrder(getToken(), Utils.getRequestBody(jsonObject));


                        }
                    }, false);


                }
            });

            ivDialogDelete.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    dismiss();
                }
            });


        }

        // 设置最大宽度，看需要而定，
        @Override
        protected int getMaxWidth() {
            return super.getMaxWidth();
        }

        @Override
        protected int getMaxHeight() {
            return super.getMaxHeight();
        }

        @Override
        protected PopupAnimator getPopupAnimator() {
            return super.getPopupAnimator();
        }

        protected int getPopupWidth() {
            return 0;
        }

        protected int getPopupHeight() {
            return 0;
        }


        private List<TenantIdPayMethod.Data> payMethodList;

        public List<TenantIdPayMethod.Data> getPayMethodList() {
            return payMethodList;
        }

        public void setPayMethodList(List<TenantIdPayMethod.Data> payMethodList) {
            this.payMethodList = payMethodList;
        }

    }


    //*********************************start***********************************//


    class QrCodeCenterPopup extends CenterPopupView {
        //注意：自定义弹窗本质是一个自定义View，但是只需重写一个参数的构造，其他的不要重写，所有的自定义弹窗都是这样。
        public QrCodeCenterPopup(@NonNull Context context) {
            super(context);
        }

        // 返回自定义弹窗的布局
        @Override
        protected int getImplLayoutId() {
            return R.layout.dialog_order_qrcode;
        }

        // 执行初始化操作，比如：findView，设置点击，或者任何你弹窗内的业务逻辑
        @Override
        protected void onCreate() {
            super.onCreate();
            TextView tvQrcodeTime = findViewById(R.id.tv_qrcode_time);
            ImageView ivQrCode = findViewById(R.id.iv_qr_code);
            TextView tvUseStatus = findViewById(R.id.tv_use_status);
            ImageView ivDelete = findViewById(R.id.iv_delete);

            TextView tvUseNum = findViewById(R.id.tv_use_num);

            tvUseStatus.setText("剩余" + qrcodeBean.getData().getCanUseNum() + "次");
//            tvUseNum.setText(qrcodeBean.getData().getEquityType());
            tvQrcodeTime.setText("此二维码" + qrcodeBean.getData().getTime() + "分钟内有效");


//            try {
            if(qrcodeBean.getData().getBase64Data().contains(",")){
                String[] split = qrcodeBean.getData().getBase64Data().split(",");
                LogUtils.e("sp--" + split[1]);
                byte[] decodedString = Base64.decode(split[1], Base64.DEFAULT);
                //系统api加载，byte转bitmap
                Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);

                ivQrCode.setImageBitmap(decodedByte);
            }


            ivDelete.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    dismiss();
                }
            });
        }

        // 设置最大宽度，看需要而定，
        @Override
        protected int getMaxWidth() {
            return super.getMaxWidth();
        }

        // 设置最大高度，看需要而定
        @Override
        protected int getMaxHeight() {
            return super.getMaxHeight();
        }

        // 设置自定义动画器，看需要而定
        @Override
        protected PopupAnimator getPopupAnimator() {
            return super.getPopupAnimator();
        }

        /**
         * 弹窗的宽度，用来动态设定当前弹窗的宽度，受getMaxWidth()限制
         *
         * @return
         */
        protected int getPopupWidth() {
            return 0;
        }

        /**
         * 弹窗的高度，用来动态设定当前弹窗的高度，受getMaxHeight()限制
         *
         * @return
         */
        protected int getPopupHeight() {
            return 0;
        }

        private QrcodeBean qrcodeBean;

        public QrcodeBean getQrcodeBean() {
            return qrcodeBean;
        }

        public void setQrcodeBean(QrcodeBean qrcodeBean) {
            this.qrcodeBean = qrcodeBean;
        }


    }


    //*********************************end***********************************//

}
